package com.leyou.user.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/13 0013
 * Time: 14:01
 */
@Service
public class UserServiceImpl implements UserService {
    private static final String SMS_KEY_PREFIX_CODE = "user:sms:code";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Boolean checkUser(String data, Integer type) {
        if (data == null) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //只需要统计次数即可
        int selectCount = userMapper.selectCount(user);
        return selectCount == 0;
    }

    @Override
    public void register(User user, String code) {
        // 检验验证码
        // 从redis中取出验证码
        String redisCode = redisTemplate.opsForValue().get(user.getPhone());
        // 比对
        if (!StringUtils.equals(redisCode, code)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        // 加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        int insert = userMapper.insertSelective(user);
        if (insert != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    @Override
    public UserDTO queryUserByUserNameAndPassword(String username, String password) {
        User user = new User();
        user.setUsername(username);
        //判断用户是否存在  根据用户名查找
        User queryUser = userMapper.selectOne(user);
        if (queryUser == null) {
            throw new LyException(ExceptionEnum.INVALID_LOGIN_USERNAME);
        }
        // 密码校验
        if (!passwordEncoder.matches(password, queryUser.getPassword())) {
            throw new LyException(ExceptionEnum.INVALID_LOGIN_PASSWORD);
        }
        return BeanHelper.copyProperties(queryUser, UserDTO.class);
    }

    @Override
    public void code(String phone) {
        // 1 校验格式
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        // 2 随机6位数
        String code = RandomStringUtils.randomNumeric(6);
        //存放在redis
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        HashMap<String, String> msg = new HashMap<>(2);
        msg.put(SMS_KEY_PREFIX_CODE + "phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

}
